package com.rockcent.mall.controller;

import com.aliyun.oss.OSSClient;
import com.rockcent.common.common.JsonResult;
import com.rockcent.common.common.RestDoing;
import com.rockcent.common.controller.BaseController;
import com.rockcent.common.domain.enumclass.Whether;
import com.rockcent.mall.Prop;
import com.rockcent.mall.Routes;
import com.rockcent.mall.lib.domain.CateTemplate;
import com.rockcent.mall.lib.domain.UploadImageFile;
import com.rockcent.mall.lib.domain.enumclass.UploadFileBusinessType;
import com.rockcent.mall.lib.dto.UploadImageFileDto;
import com.rockcent.mall.lib.dto.UserInfoDto;
import com.rockcent.mall.lib.helper.BaseUserHelper;
import com.rockcent.mall.lib.repository.CateTemplateRepository;
import com.rockcent.mall.lib.repository.UploadImageFileRepository;
import org.apache.commons.lang3.EnumUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.List;

/**
 * Created by zhangjh on 2016/10/21.
 */
@RestController
public class CateTemplateController extends BaseController {

    private final Logger log = LoggerFactory.getLogger(CateTemplateController.class);

    private final String SERVER_URL="http://uploads.rockcent.com";

    @Autowired
    private CateTemplateRepository cateTemplateRepository;

    @Autowired
    private OSSClient ossClient;
    @Autowired
    private UploadImageFileRepository uploadImageFileRepository;
    @Autowired
    private Prop prop;

    @Autowired
    private BaseUserHelper userHelper;

    /**
     * @api {get} /mall/category/templates/list 类目图标列表
     * @apiGroup mall_category
     * @apiVersion 1.0.0
     *
     * @apiHeader {String} userToken 用户token
     * @apiHeader {String} domain 请求域名
     *
     * @apiSuccessExample {json} Success-Response:
     * {
     * "code": "1",
     * "desc": "成功",
     *     "data": [
     *      {
     *        "id": 1,
     *        "dateCreated": "2016-07-29 14:50:16",
     *        "lastUpdated": "2016-10-21 13:15:24",
     *        "version": 0,
     *        "name": "健康食品",
     *        "iconUrl": "http://uploads.rockcent.com/category/food.png",
     *        "sort": 1
     *     }...
     *     ]
     * }
     */
    @RequestMapping(value = Routes.MALL_CATEGORY_TEMPLATE_LIST,method = RequestMethod.GET)
    public JsonResult listCateTemplate(HttpServletRequest request){
        UserInfoDto userInfoDto=userHelper.getSession(request);
        RestDoing doing = jsonResult -> {
          List<CateTemplate> result= cateTemplateRepository.findByIsDelete(Whether.NO);
            result.forEach(cateTemplate -> {
                cateTemplate.setIconUrl(SERVER_URL+cateTemplate.getIconUrl());
            });
            jsonResult.data=result;
        };
        return  doing.go(request,log);
    }

    /**
     * @api {post} /mall/category/templates/upload 类目 图标上传
     * @apiGroup mall_category
     * @apiVersion 1.0.0
     * @apiHeader {String} userToken 用户token
     * @apiHeader {String} domain 请求域名
     * @apiParam {File} file <code>必须参数</code>文件
     * @apiParam {String} businessType <code>必须参数 CATE_TEMPLATE_ICON</code> 业务类型
     * @apiSuccessExample {json} Success-Response:
     * {
     * "code": "1",
     * "desc": "成功",
     * }
     */
    @RequestMapping(value = Routes.MALL_CATEGORY_TEMPLATE_UPLOAD,method = RequestMethod.POST)
    public JsonResult uploadCateTemplate(MultipartFile file, String businessType, HttpServletRequest request) {

        UserInfoDto userInfoDto = userHelper.getSession(request);
        RestDoing restDoing = jsonResult -> {
            if (file == null) {
                jsonResult.errorParam("file 不能为空",log);
                return;
            }
            if (businessType == null) {
                jsonResult.errorParam("businessType 不能为空",log);
                return;
            }

            if (!EnumUtils.isValidEnum(UploadFileBusinessType.class, businessType)) {
                jsonResult.remind("业务类型 只允许 CATE_TEMPLATE_ICON(\"/category\",\"分类图标\")",log);
                return;
            }

            UploadImageFileDto uploadImageFileDto = this.doUpload(file, businessType, userInfoDto);
            if(uploadImageFileDto==null || StringUtils.isBlank(uploadImageFileDto.getPath())){
                jsonResult.remind("上传失败",log);
                return;
            }
            jsonResult.data=uploadImageFileDto;
//            CateTemplate cateTemplate=new CateTemplate();
//            cateTemplate.setIconUrl(uploadImageFileDto.getPath());
//            cateTemplate.setName("类目图标");
//            cateTemplate.setSort(new Integer(0));
//            cateTemplateRepository.saveAndFlush(cateTemplate);
        };

        return restDoing.go(request, log);
    }

    private UploadImageFileDto doUpload(MultipartFile file, String businessType, UserInfoDto userInfoDto) throws IOException {
        UploadImageFile uploadImageFile = new UploadImageFile();
        // 文件名
        String fileName = uploadImageFile.genFileName(file.getOriginalFilename());
        String allPath = uploadImageFile.genAllPath(prop.env, UploadFileBusinessType.valueOf(businessType), fileName);

        uploadImageFile.setSize(file.getSize());
        uploadImageFile.setOriginFileName(file.getOriginalFilename());
        uploadImageFile.setFileName(fileName.toString());
        uploadImageFile.setPath("/" + allPath);
        uploadImageFile.setBusinessType(UploadFileBusinessType.valueOf(businessType));
        uploadImageFile.setUserInfoId(userInfoDto.getId());
        uploadImageFile.setMerchantId(userInfoDto.merchant.getId());
        uploadImageFile.setMallId(userInfoDto.mall.getId());
        uploadImageFile = uploadImageFileRepository.save(uploadImageFile);

        ossClient.putObject(prop.aliyunOssBucketName, allPath, file.getInputStream());

        UploadImageFileDto uploadImageFileDto = new UploadImageFileDto();
        uploadImageFileDto.setPath(uploadImageFile.getPath());
        uploadImageFileDto.setId(uploadImageFile.getId());
        return uploadImageFileDto;
    }
}
